﻿using System.Linq.Expressions;

namespace Seagull.Internal
{
    /// <summary>
    /// 基于反射和表达式树相结合的方式，进行对象的深拷贝。
    /// 基于(https://www.cnblogs.com/lsgsanxiao/p/8205096.html)改编
    /// </summary>
    public static class TransExp
    {
        /// <summary>
        /// 深拷贝指定的对象。
        /// </summary>
        /// <typeparam name="TIn">需要深拷贝的对象类型</typeparam>
        /// <param name="tIn">需要深拷贝的对象实例</param>
        /// <returns></returns>
        public static TIn Trans<TIn>(TIn tIn)
        {
            return TransExp<TIn, TIn>.Trans(tIn);
        }
    }

    /// <summary>
    /// 基于反射和表达式树相结合的方式，进行对象的深拷贝。
    /// 基于(https://www.cnblogs.com/lsgsanxiao/p/8205096.html)改编
    /// </summary>
    /// <typeparam name="TIn">输入的对象类型</typeparam>
    /// <typeparam name="TOut">输出的对象类型</typeparam>
    static class TransExp<TIn, TOut>
    {
        private static readonly Func<TIn, TOut> cache = GetFunc();
        private static Func<TIn, TOut> GetFunc()
        {
            List<MemberBinding> memberBindingList = new();
            ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");

            foreach (var item in typeof(TOut).GetProperties())
            {
                if (!item.CanWrite)
                    continue;

                MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }

            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
            Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });

            return lambda.Compile();
        }

        public static TOut Trans(TIn tIn)
        {
            return cache(tIn);
        }
    }
}
